home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / TPTUTR0F.ZIP / PASCAL4.TXT < prev    next >
Text File  |  1996-01-02  |  12KB  |  297 lines

  1.                   Turbo Pascal for DOS Beginning Tutorial
  2.                               by Glenn Grotzinger
  3.                  Part 4 -- Writing Procedures and Functions
  4.            all parts copyright 1995-96 (c) by Glenn Grotzinger.
  5.  
  6.         Hello, again, and lets get started...
  7.  
  8. An example of a solution of last week's programming problem:
  9.  
  10. program part3;
  11.  
  12.   { This program enables a user to play a guessing game.
  13.     Range: 1-100     Guesses: 6 }
  14.  
  15.   var
  16.     choice: char;
  17.     randnum, number_given, attempts: integer;
  18.  
  19.   begin
  20.     randomize; { start random # generator }
  21.     while upcase(choice) <> 'N' do   { while we want to play }
  22.       begin
  23.         randnum := random(100) + 1;  { generate random number for game }
  24.         attempts := 6; { set initial number of attempts }
  25.         number_given := 1000; { stuff number_given so while kicks in }
  26.         writeln('I''m thinking of a number between 1 and 100.  What is it?');
  27.         while (attempts > 0) and (number_given <> randnum) do
  28.            { while we still have attempts to guess }
  29.           begin
  30.             readln(number_given);
  31.             if number_given = randnum then
  32.                writeln('Congratulations!  You got the number right!')
  33.             else
  34.                begin
  35.                  attempts := attempts - 1;
  36.                  if attempts = 0 then
  37.                    writeln('Sorry, you ran out of choices. ',
  38.                            ' The number I was thinking of is ',
  39.                            randnum, '.')
  40.                  else
  41.                    if number_given > randnum then
  42.                      writeln('It''s lower.  (', attempts,
  43.                            ' guesses remaining)')
  44.                    else
  45.                      writeln('It''s higher. (', attempts,
  46.                            ' guesses remaining)');
  47.               end;
  48.           end;
  49.         writeln;
  50.         writeln('Do you want to play again? (Y/N)');
  51.         readln(choice);
  52.       end;
  53.    end.
  54. If there are any questions or difficulties, write ggrotz@2sprint.net.
  55.  
  56. On to the new stuff...
  57.  
  58. PROCEDURE writing
  59. =================
  60.         This is a way a lot of things work in Pascal.  For example, the
  61. write command is a procedure.  We say the procedure name, then a list of
  62. parameters which describe what we want to write.  Write is defined in
  63. Pascal itself, but we can write our own procedures to do things.  Before
  64. the main part of the program, and after our variable declarations, we
  65. place our procedures.  Procedures are essentially whole separate programs
  66. which perform small tasks in a bigger program. Here is a short example of
  67. what I mean:
  68.  
  69. program tutorial11;
  70.  
  71.   var
  72.     one, two: integer;
  73.     final: integer;
  74.  
  75.   procedure addtwonumbers(first, second: integer; var answer: integer);
  76.     begin
  77.       answer := first + second;
  78.     end;
  79.  
  80.   begin
  81.     writeln('Adding two numbers:');
  82.     writeln('Type two numbers in (space after each number) to add.');
  83.     readln(one, two);
  84.     addtwonumbers(one, two, final);
  85.     writeln('The answer is ', final, '.');
  86.   end.
  87.  
  88. The procedure enables us to perform more modular, understandable, and
  89. easier to debug programs.  We always code logical parts of the program
  90. together in procedures and functions (will be discussed later).  This
  91. example is pretty simplistic, as we include only one statement in a
  92. procedure (generally a waste of time), which could easily be in the body
  93. of the program.  We can use one statement procedures in more logical things,
  94. such as conversions of one set of unit to another.  We describe the parts
  95. of the procedure declaration above, and the calling of the procedure.
  96.  
  97. We can define a series of statements as long as they are the same type, and
  98. we don't want to keep them without the use of the VAR section of the
  99. procedure.  We don't care about, and don't modify first, and second, so we
  100. place them in there without the var.  We modify the variable used as
  101. answer, so we MUST have the VAR before it in order to have the variable
  102. survive in a modified state by calling the procedure.  Play around with
  103. what happens in tutorial11 when you remove the var from in front of the
  104. third statement.  When we call the procedure, we use variables which match
  105. and make sense to what we want each variable we want. we use one, and two
  106. for the numbers to add, because our procedure is designed
  107. to add those first two numbers.  Then we put final in the last one, because
  108. that is our final answer.  We can SAFELY use the same variable names for
  109. the procedure and the globals, but it is a good idea not to, as it will not
  110. always be possible to correlate our items in that way.  We should always
  111. have a goal to write procedures/functions with ability to drop them into
  112. another program where all the parameters are passed to it.  We can easily
  113. drop the procedure written above into any other program that needs a similar
  114. function.  It is possible to have a parameterless procedure as well, if it
  115. is predicted as required.  Say...In a multi-function menu system or something
  116. that does a set thing (clrscr is an example).
  117.  
  118. NOTE: It is always good to keep your old code when you write and use
  119. parameter passing in your procedures and functions, so you can easily 
  120. re-use your code and save time in having to rewrite old code.
  121.  
  122. FUNCTION writing
  123. ================
  124. Function declarations are exactly like procedures, except that functions
  125. have the capability to return a value.  We see in the example, below, which
  126. is a rewrite of tutorial11.
  127.  
  128. program tutorial12;
  129.   var
  130.     one, two: integer;
  131.     final: integer;
  132.  
  133.   function addtwonumbers(first, second: integer):integer;
  134.     var
  135.       answer: integer;
  136.     begin
  137.       answer := first + second;
  138.       addtwonumbers := answer;
  139.       {we can also do addtwonumbers := first + second;}
  140.     end;
  141.  
  142.   begin
  143.     writeln('Adding two numbers:');
  144.     writeln('Type two numbers in (space after each number) to add.');
  145.     readln(one, two);
  146.     final := addtwonumbers(one, two);
  147.     writeln('The answer is ', final, '.');
  148.   end.
  149.  
  150. In the function, we see we MUST define the final answer to the value of
  151. the function.  The end part :integer; defines the return value of the
  152. function.  The way to set up a function should be evident from this example.
  153.  
  154. SETS
  155. ====
  156. It's possible in an IF/WHILE/REPEAT to set up a test on a group of statements.
  157. For example:
  158.    IF character in ['a'..'z'] then
  159.    { if character is in the lowercase alphabet }
  160.    IF character in ['1','2','3','5']
  161.    { if character is 1, 2, 3, or 5 }
  162.    IF number in [0..23] then
  163.    { if number is between 0 and 23 }
  164.  
  165. TYPE and CONST statements.
  166. ==========================
  167. It's possible to type-delineate variables.  Such as for example, we may want
  168. to limit a string from it's standard 255 characters (if we say just string),
  169. to say 10 characters (string[10]), we can not use something like that in
  170. a procedure or function (we will see the types used a lot).  Therefore, we
  171. use the type section to redefine this so we can use them in procedures/
  172. functions.
  173.  
  174. It's also possible to set constants in a pascal program.  Say, if we want
  175. to set up a constant tax rate, we just define it in a constant section.
  176.  
  177. We see this in an example:
  178.  
  179. program tutorial13;
  180.   const
  181.     tax_rate = 0.14; {14% tax rate}
  182.   type
  183.     string[15] = string15;
  184.     { string[15] redefined so we can use it in a procedure/function,
  185.       though we will not have procedures or functions here. }
  186.   var
  187.     total_pay: real;
  188.     your_name: string15;
  189.     {if we make type dec, we must carry it across.  This variable is
  190.      a string with a limit of 15 characters. }
  191.   begin
  192.     writeln('Who are you? (15 char. max)');
  193.     readln(your_name);
  194.     writeln('How much did you earn this paycheck?');
  195.     readln(total_pay);
  196.     writeln('Assuming, you have a ', tax_rate * 100 :0:0, '% income tax ',
  197.             'rate, you will have to pay $', total_pay * tax_rate :0:2,
  198.             ' in income tax this paycheck.');
  199.   end.
  200.  
  201. The use of tax_rate is a prime reason that we would want to define a
  202. constant.  Instead of using that number everywhere we needed it, we used
  203. the reference of tax_rate.  Why?  If the income tax ever changed in this
  204. example, we would not need to go through the whole program and change that
  205. number.  All we need to do is change that reference.
  206.     
  207. Clearing the screen
  208. ===================
  209. This will be the first example of a command that we must call a unit for
  210. to get.  The unit you call (as I did in tutorial1) would be CRT for TP/DOS,
  211. and WINCRT for TP/WIN.  You use the statement clrscr; for this.  This
  212. program example clears the screen.
  213.  
  214. program tutorial14; uses crt;
  215.   begin
  216.     clrscr;
  217.     writeln('I cleared the screen for you.');
  218.   end.
  219.  
  220. Final Note
  221. -=========
  222. You should lay out your programs in logical units using functions and
  223. procedures, making them parameter passing if possible, and logical.
  224. The best may be (especially for programs that do multiple things which
  225. are unrelated on code level) to not parameter pass.  Whatever works
  226. functionally is the best, and if you can't figure out a way to parameter
  227. pass to the procedure or function....
  228.  
  229. Programming Practice Problem Notes
  230. ==================================
  231.         This is the first program, that I would expect you to write using
  232. functions and procedures.  All programs you should write in the future
  233. should strive to use parameter-passed procedures.  The reasons are many-
  234. fold for this, which I stated before.  Be sure you do this.  This program
  235. should not be any more difficult than any of the previous programming
  236. problems I gave.  All I expect this one to be is an exercise for you to
  237. learn in using procedures and functions.  If you want more practice beyond
  238. this problem in writing things using procedures and parameters, I suggest
  239. you recode the programming problem out of part 2.  If you can get it more
  240. easier understood to look at, and using parameter-passed procedures for the
  241. logical parts of it, and make it work right, then you got it.
  242.  
  243. Practice Programming Problem #4
  244. ===============================
  245.         Write a program in pascal and entirely Pascal which will present
  246. a simple menu driven system (readable, and by pages -- use clrscr in the
  247. appropriate spots) which will enable the user by choice to do the following,
  248. as indicated by sample output for the menu.
  249.  
  250. sample output for menu
  251. ======================
  252. 1. Convert a number of seconds to hours, minutes, and seconds.
  253. 2. Convert a given military time to AM/PM time.
  254. 3. Quit the program.
  255.  
  256. Please enter your choice now:
  257.  
  258. sample output for option 1
  259. ==========================
  260. Please enter a number of seconds: 3600
  261.  
  262. 3600 seconds is 1 hour, 0 minutes, and 0 seconds.
  263.  
  264. Press ENTER to continue:
  265.  
  266. sample output for option 2
  267. ==========================
  268. Enter a military time's hours: 14
  269. Enter a miltiary time's seconds: 00
  270.  
  271. It is 2:00 PM.
  272.  
  273. Press ENTER to continue:
  274. ================
  275.  
  276. Notes: 1. there are 60 seconds in a minute, 60 minutes in an hour.
  277.        2. "military time" is 24-hr time.  For example, 16:00 would be
  278.           4 P.M.
  279.        3. The program must continue to function in the menu system until
  280.           the user wishes to quit.
  281.        4. Remember to ask the user for appropriate data that you need.
  282.        5. Be sure to pause the screen to enable the user to see the results
  283.           of their query.  You may accomplish this by just calling readln;.
  284.           It will call the computer to wait until the user presses a key.
  285.        6. Be SURE your program is easily understood.
  286.  
  287.  
  288. The solution to this program will be presented in the next part.  Good luck!
  289.  
  290. Next time
  291. =========
  292.         Next time, we will discuss the usage of text files for reading in
  293. data and writing out results. We really are moving along with the concepts
  294. rather readily...
  295.  
  296.  
  297.